package com.example.springbootproject.controller;/*
 *@author 王志威
 *@datatime 2024/4/14 15:56
 *@editnote
 */

import com.example.springbootproject.pojo.Admin;
import com.example.springbootproject.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

@Controller
@Slf4j(topic = "login")
@RequestMapping("/user")
@Validated
public class LoginController {
    @Autowired
    private LoginService loginService;

    //登录主界面
    @GetMapping("/loginMain")
    protected String loginMain() {
        log.error("进入登录主界面");
        return "LoginMain";
    }

    //登录
    @PostMapping(value = "/login")
    protected String login(@RequestParam @NotNull(message = "用户名不能为空") @Size(min = 3, max = 6, message = "用户名长度在3-6之间") String username, @RequestParam String encryptedPassword, HttpSession session, Model model) throws NoSuchAlgorithmException {
        //验证用户名和密码
        Admin admin = loginService.login(username, encryptedPassword);
        log.info("用户名：" + username + "密码：" + encryptedPassword);
        if (admin != null) {
            //重定向到主页
            //并把session存入
            session.setAttribute("user", username);
            log.info("用户登录成功");
            model.addAttribute("username", username);
            return "redirect:mainPage";
        } else {
            //错误，返回登录页面
            log.info("用户登录失败");
            return "redirect:loginMain";
        }
    }

    //主界面
    @RequestMapping("/mainPage")
    protected String mainPage() throws ServletException, IOException {

        return "MainPage";
    }

}
